﻿using System;
using System.Collections.Generic;
using System.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace JiveMessenger.Utilities
{
    public static class ListViewHelper
    {
        #region SetFixedWidthOnItemsPanel

        public static bool GetSetFixedWidthOnItemsPanel(ListView element)
        {
            return (bool)element.GetValue(SetFixedWidthOnItemsPanelProperty);
        }

        public static void SetSetFixedWidthOnItemsPanel(ListView element, bool value)
        {
            element.SetValue(SetFixedWidthOnItemsPanelProperty, value);
        }

        public static readonly DependencyProperty SetFixedWidthOnItemsPanelProperty = DependencyProperty.RegisterAttached(
        "SetFixedWidthOnItemsPanel",
        typeof(bool),
        typeof(ListViewHelper),
        new PropertyMetadata(false, OnSetFixedWidthOnItemsPanelChanged));

        private static void OnSetFixedWidthOnItemsPanelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var element = (ListView)d;
            var oldValue = (bool)e.OldValue;
            var newValue = (bool)e.NewValue;

            if (oldValue)
            {
                element.SizeChanged -= OnListViewSizeChanged;
            }

            if (newValue)
            {
                element.SizeChanged += OnListViewSizeChanged;
            }
        }

        private static void OnListViewSizeChanged(object sender, SizeChangedEventArgs e)
        {
            var listView = (ListView)sender;
            var itemsStackPanel = listView.ItemsPanelRoot as ItemsStackPanel;
            if (itemsStackPanel != null)
            {
                itemsStackPanel.Width = e.NewSize.Width;
            }
        }

        #endregion
    } 
}
